﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using MAPIdotnet;
using OutlookHub.Styles;
using OutlookHub.Models;
using Silvermoon.Windows.Styles;
using OutlookHub.Utils;
using Silvermoon.UI;
using OutlookHub.Controllers;
using OutlookHub.Classes;

namespace OutlookHub.Pages
{
    public class EMailFoldersPage : Page
    {
        private ListView listView;
        private ListViewController<TitleCountItem, Folder> controller;

        public EMailFoldersPage()
            : base()
        {
            Title = "FOLDERS";

            Styles = StylePool.EMails;
            listView = new ListView { Margin = Margin.Zero };
            SetTransition(350, TransitionMask.RotateLeftIn, TransitionMask.RotateLeftIn);
            Controls.Add(listView);

            controller = new ListViewController<TitleCountItem, Folder>(listView) { ItemHeight = 80 };
            controller.ItemStyle = new TextItemStyle { Font = FontPool.MediumRegularFont, Margin = new Margin(10, 0, 10, 0) };
            controller.UpdateItem += new EventHandler<ItemControlGeneratorEventArgs<TitleCountItem>>(controller_UpdateItem);
            controller.InitializeItem += new EventHandler<ItemControlGeneratorEventArgs<TitleCountItem>>(controller_InitializeItem);

            LoadData();
        }

        void controller_InitializeItem(object sender, ItemControlGeneratorEventArgs<TitleCountItem> e)
        {
            e.Item.Tap += new EventHandler<TapEventArgs>(OnItemTap);
        }

        void OnItemTap(object sender, TapEventArgs e)
        {
            Item item = sender as Item;

            Folder folder = item.DataValue as Folder;
            EMailContext.Context.CurrentFolder = folder;
            GoBack();

        }

        protected override void OnShown()
        {
            base.OnShown();
            //LoadData();
        }

        private void LoadData()
        {
            var ctrl = EMailContext.Context;
            controller.DataSource = ctrl.Folders.Where(f => f.MailCount > 0);
        }

        void controller_UpdateItem(object sender, ItemControlGeneratorEventArgs<TitleCountItem> e)
        {
            Folder folder = e.Value as Folder;
            //e.Item.Text = folder.Name + " (" + folder.MailCount.ToString() + ")";
            e.Item.Text = folder.Name;
            e.Item.IsSelected = folder.Id == EMailContext.Context.CurrentFolder;
            e.Item.Count = folder.MailCount;
        }

    }
}
